package com.oig.sys.security.config;

import com.oig.common.constants.CommonConstants;
import com.oig.common.module.SysResponse;
import com.oig.common.util.JsonUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 授权失败信息包装 oauth2没有权限抛出 AccessDeniedException
 */
public class ResourceAccessDeniedHandler implements AccessDeniedHandler {

    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException)
            throws IOException {

        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.FORBIDDEN.value());

        PrintWriter printWriter = response.getWriter();
        SysResponse<String> sysResponse = SysResponse.failed();
        if (authException != null) {
            sysResponse.setMsg("您没有权限，禁止访问");
            sysResponse.setData(authException.getMessage());
        }
        printWriter.write(JsonUtil.toJSONString(sysResponse));
        printWriter.flush();
        printWriter.close();
    }

}
